<?php
/**
 * Enter description here ...
 * @author NgoAnhTu
 * @date 2013-11-07
 */
class NewsBusiness {
		
	private static $instance = null;
	
	/**
	 * Enter description here ...
	 * @var NewsDAO
	 */
	private $newsDAO;
	
	/**
	 * Enter description here ...
	 * @var NewsCategoryDAO
	 */
	private $newsCategoryDAO;
	
	/**
	 * Enter description here ...
	 * @var LanguageDAO
	 */
	private $langDAO;
		
	/**
	 * NewsBusiness instance only
	 * @return NewsBusiness
	 */
	public static function getInstance() {
		if (self::$instance == null)
			self::$instance = new NewsBusiness();
		return self::$instance;
	}
		
	/**
	 * Constructor
	 */
	public function NewsBusiness() {
		$this->newsDAO = NewsDAO::getInstance();
		$this->newsCategoryDAO = NewsCategoryDAO::getInstance();
		$this->langDAO = LanguageDAO::getInstance();
	}

	/**
	 * Search NewsCategory
	 * @param string $lang
	 * @param integer $pageIndex
	 * @param string $pattern
	 */
	public function searchCategories($lang = 'en', $pageIndex = 1, $pattern = '') {
		return $this->newsCategoryDAO->selectPage($pageIndex, DAO::PAGE_SMALL, "Lang = '$lang' AND Name LIKE '$pattern%'", "Name");
	}
	
	/**
	 * Search News
	 * @param integer $cid
	 * @param integer $pageIndex
	 * @param string $pattern
	 */
	public function searchNews($cid, $pageIndex = 1, $pattern = '') {
		$pattern = str_replace(' ', '%', trim($pattern, '  '));
		return $this->newsDAO->selectPage($pageIndex, DAO::PAGE_SMALL, "Category = $cid " .
											"AND (Title LIKE '%$pattern%' " . 
											"OR Header LIKE '%$pattern%' " .
											"OR Body LIKE '%$pattern%') ", "CreateDate", DAO::DESC);
	}

	/**
	 * Active many News categories
	 * @param array $idArray
	 */
	public function activeCaterories($idArray) {
		$ids = "''";
		if (sizeof($idArray) > 0) {
			foreach ($idArray as $id) {
				$ids .= ",'$id'";
			}
		}
		$this->newsCategoryDAO->active($ids);
	}
	
	/**
	 * Active many News 
	 * @param array $idArray
	 */
	public function active($idArray) {
		$ids = "''";
		if (sizeof($idArray) > 0) {
			foreach ($idArray as $id) {
				$ids .= ",'$id'";
			}
		}
		$this->newsDAO->active($ids);
	}

	/**
	 * Check exist NewsCategory
	 * @param string $lang
	 * @param string $name
	 * @return boolean
	 */
	public function isCategoryExist($lang, $name) {
		return $this->newsCategoryDAO->isExist(new NewsCategory(), "Name LIKE '$name' AND LANG='$lang'");
	}
	
	/**
	 * Check exist News 
	 * @param string $title
	 * @return boolean
	 */
	public function isExist($title) {
		return $this->newsDAO->isExist(new News(Entity::NEW_ID), "Title LIKE '$title'");
	}

	/**
	 * Check exist News 
	 * @param unknown_type $id
	 * @param unknown_type $name
	 * @return boolean
	 */
	public function isExistCategoryOther($id, $name, $lang) {
		return $this->newsCategoryDAO->isExistOther(new NewsCategory($id, $name, 0, $lang));
	}
	
	/**
	 * Check exist News 
	 * @param unknown_type $id
	 * @param unknown_type $name
	 * @return boolean
	 */
	public function isExistOther($id, $name, $lang) {
		return $this->newsDAO->isExistOther(new News($id, $name), "Lang = '$lang'");
	}
	
	/**
	 * Create new NewsCategory
	 * @param string $lang
	 * @param string $name
	 * @return Ambigous <Entity, NULL>
	 */
	public function createCategory($lang, $name) {
		$cat = new NewsCategory(0, $name, 0, $lang);
		return $this->newsCategoryDAO->insert($cat);
	}

	/**
	 * Update NewsCategory
	 * @param NewsCategory $cat
	 * @return Ambigous <Entity, NULL>
	 */
	public function updateCategory($cat) {
		return $this->newsCategoryDAO->update($cat);
	}
	
	/**
	 * Save news
	 * @param integer $cid
	 * @param string $title
	 * @param string $header
	 * @param string $body
	 * @param string $author
	 */
	public function create($cid, $title, $header, $body, $author) {
		$news = new News(Entity::NEW_ID, $title, $header, $body, $author);
		$news->createDate = Date::now();
		$news->category = $cid;
		return $this->newsDAO->insert($news);
	}
	
	/**
	 * Enter description here ...
	 * @param News $news
	 * @param Image $image
	 * @param array $names
	 * @param array $codes
	 */
	public function update($news, $image, $names, $codes) {
		$oldImage = null;
		$newImage = null;
		$image = new Image($image);
		if ($image->size > 0) {
			$oldImage = $news->image;
			$news->image = $image->thumbnail(Properties::ALBUM_DIR, self::ALBUM_THUMB_WIDTH, self::ALBUM_THUMB_HEIGHT, String::filter(String::firstWork($news->name)) . '.' .Image::EXT_PNG, false, 10);
			$newImage = $news->image;
			if ($oldImage == $newImage) {
				$oldImage = null;
			}
			$image->destroy();
		}
		
		$this->newsDAO->beginTransaction();
		$news = $this->newsDAO->update($news);
		
		if ($news != null) {
			for ($i = 0; $i < sizeof($names); $i++) {
				$detail = $this->newsCategoryDAO->getDetail($news->id, $codes[$i]);
				if ($detail != null) {
					$detail->content = $names[$i];
					if ($this->newsCategoryDAO->update($detail) == null) {
						$this->newsCategoryDAO->rollback();
						$image->del($newImage);	
						return null;
					}
				} else {
					$detail = new NewsCategory(Entity::NEW_ID, $news->id, $codes[$i], $names[$i]);
					if ($this->newsCategoryDAO->insert($detail) == null) {
						$this->newsCategoryDAO->rollback();
						$image->del($newImage);	
						return null;
					}
				}
			}
			$image->del($oldImage);	
		}
		
		$this->newsDAO->commit();
		return $news;
	}

	/**
	 * Find by NewsCategory ID
	 * @param string $id
	 * @return NewsCategory
	 */
	public function findCatById($id, $lang = '') {
		return  $this->newsCategoryDAO->selectById(new NewsCategory($id));
	}
	
	/**
	 * Find by News code
	 * @param string $id
	 * @return News
	 */
	public function findById($id) {
		$news = $this->newsDAO->selectById(new News($id));
		if ($news != null) {
			$news->details = $this->newsCategoryDAO->getDetails($id);
		}
		return $news;
	}
	
	/**
	 * Enter description here ...
	 * @param integer $id
	 * @return Ambigous <boolean, resource>
	 */
	public function cdel($id) {
		return $this->newsCategoryDAO->delete(new NewsCategory($id));
	} 
	
	/**
	 * Enter description here ...
	 * @param unknown_type $id
	 * @return Ambigous <boolean, resource>
	 */
	public function del($id) {
		return $this->newsDAO->delete(new News($id));
	} 
	
	/**
	 * Enter description here ...
	 * @param integer $newsId
	 */
	public function getPics($newsId) {
		return $this->langDAO->select(DAO::FIRST_PAGE, DAO::MAX_SIZE, "NewsId = $newsId", 'Order');
	}
	
	/**
	 * Enter description here ...
	 * @param integer $newsId
	 * @param array $orders
	 * @param array $imgs
	 * @return boolean
	 */
	public function insertPics($newsId, $orders, $imgs) {
		$count = 0;
		for ($i = 0; $i < sizeof($imgs["name"]); $i++) {
			$image = new Image($imgs, $i);
			if ($image->size > 0) {
				$order = $orders[$i];
				$url = $image->saveAs(Properties::ALBUM_DIR, $order . '.' . Image::EXT_PNG, self::IMG_WIDTH, $isReplace = false);
				$thumbUrl = str_replace(Properties::ALBUM_DIR . '/', '', $url);
				$image = new Image($imgs, $i);
				$thumbUrl = $image->thumbnail(Properties::ALBUM_DIR, self::IMG_THUMB_WIDTH, self::IMG_THUMB_HEIGHT, "thumb_$thumbUrl", false, 10);
				if ($url != null) {
					$image->destroy();
					$pic = new Language(0, $thumbUrl, $url, $order, $newsId);
					if ($this->langDAO->insert($pic) != null) {
						$count++;
					}
				}
			}
		}
		return $count;
	}
	
	/**
	 * Enter description here ...
	 * @param array $picIDs
	 * @param array $orders
	 */
	public function updatePicOrders($picIDs, $orders) {
		$check = true;
		$this->langDAO->beginTransaction();
		
		for ($i = 0; $i < sizeof($picIDs); $i++) {
			$pic = $this->langDAO->selectById(new Language($picIDs[$i]));
			$pic->order = $orders[$i];
			if ($this->langDAO->update($pic) == null) {
				$this->langDAO->rollback();
				$check = false;
				break;
			}
		}
		
		$this->langDAO->commit();
		return $check;
	}
	
	/**
	 * Enter description here ...
	 * @param array $delIDs
	 */
	public function deletePics($delIDs) {
		$check = true;
		$this->langDAO->beginTransaction();
		$img = new Image();
		
		for ($i = 0; $i < sizeof($delIDs); $i++) {
			$pic = $this->langDAO->selectById(new Language($delIDs[$i]));
			if ($pic != null) {
				if (!$this->langDAO->delete(new Language($delIDs[$i]))) {
					$this->langDAO->rollback();
					$check = false;
					break;
				} else {
					$img->del($pic->image);
					$img->del($pic->thumb);
				}
			}
		}
		
		$this->langDAO->commit();
		return $check;		
	}
	
}
?>